#import "Board.h"
#import "globals.h"

@implementation Board

- (void)drawRect:(NSRect)rect 
{
    float extraHeight = [self frame].size.height-(squareSize*boardSize);
    NSPoint point = {0, extraHeight};
    int i, j;
    time_t today;
    struct tm *tmToday;
    int prevPiece = kEmpty;

    BoardData *data = [history currentItem],
	      *prevData = [history previousItem];
    [data retain];
    if (prevData == nil)
    {
	prevData = [[BoardData alloc] init];
        markPos.x = -1;
    }
    else
	[prevData retain];

    [board compositeToPoint:point fromRect:NSMakeRect(0, squareSize*(kBoardMaxCells-boardSize), squareSize*boardSize, squareSize*boardSize) operation:NSCompositeSourceOver];
//    [board compositeToPoint:point operation:NSCompositeSourceOver];

    today = time (&today);
    tmToday = localtime (&today);
    // put santa pic in the board on xmas day!
    if ((tmToday->tm_mday == 25) && (tmToday->tm_mon == 11))
    {
        [[NSImage imageNamed:@"santa"] setScalesWhenResized:YES];
        [[NSImage imageNamed:@"santa"] setSize:NSMakeSize([self frame].size.height,
                                                     [self frame].size.height)];
        [[NSImage imageNamed:@"santa"] compositeToPoint:point
          operation:NSCompositeSourceOver fraction:0.20];
    }
    
    
    for (i = 0; i < boardSize; ++i)
    {
        for (j = 0; j < boardSize; ++j)
        {
            prevPiece = [prevData getValueAtX:j y:i] & 
                        (kWhitePiece | kBlackPiece | kLegalMove);
	    point = NSMakePoint(j*squareSize, i*squareSize + extraHeight);
            
	    switch ([data getValueAtX:j y:i] & (kWhitePiece | kBlackPiece
                                                | kLegalMove))
	    {
		case kBlackPiece:
		    if ((prevPiece != kBlackPiece) && animation)
		    {
			if (prevPiece == kWhitePiece)
			    [whitePiece compositeToPoint:point
				               operation:NSCompositeSourceOver
				                fraction:((float)animation)+1/
				    	                 kAnimationSteps];
			else
			{
                            markPos.x = j;
                            markPos.y = i;
                        }
			
			[blackPiece compositeToPoint:point
			                   operation:NSCompositeSourceOver
			                    fraction:1/((float)animation)];
		    }
		    else
                    {
			[blackPiece compositeToPoint:point
			                   operation:NSCompositeSourceOver];
                    }
		    break;
		case kWhitePiece:
		    if ((prevPiece != kWhitePiece) && animation)
		    {
			if (prevPiece == kBlackPiece)
                        {
			    [blackPiece compositeToPoint:point
				               operation:NSCompositeSourceOver
				                fraction:((float)animation)+1/
                                                        kAnimationSteps];
                        }
			else
			{
                            markPos.x = j; 
                            markPos.y = i;
                        }
			
			[whitePiece compositeToPoint:point
			                   operation:NSCompositeSourceOver
			                    fraction:1/((float)animation)];
		    }
		    else
			[whitePiece compositeToPoint:point
			                   operation:NSCompositeSourceOver];
		    break;
		case kBlackPiece | kLegalMove:
		    if ([gameController ghostsEnabled] && animation < 2)
			[blackPiece compositeToPoint:point 			  			                   operation:NSCompositeSourceOver 
			                    fraction:0.25];
		    break;
		case kWhitePiece | kLegalMove:
		    if ([gameController ghostsEnabled] && animation < 2)
			[whitePiece compositeToPoint:point 			  			                   operation:NSCompositeSourceOver 
			                    fraction:0.25];
		    break;
	    }
	
//            if ([data getValueAtX:j y:i] & kStablePiece)
//            {
//                [[plugin imageNamed:@"stable"] compositeToPoint:point 			 			operation:NSCompositeSourceOver fraction:0.80];
//            }
            if ((markPos.x == j) && (markPos.y == i))
            {
		[mark compositeToPoint:point 			 					     operation:NSCompositeSourceOver
                              fraction:0.50];
            }

        }
    }
    
    [data release];
    [prevData release];
}


- (BOOL)isOpaque
{
    return NO;
}

- (void)mouseUp:(NSEvent *)event
{
    NSPoint eventLocation = [event locationInWindow];
    NSPoint point = [self convertPoint:eventLocation fromView:nil];

    int x = point.x/squareSize,
	y = point.y/squareSize;

    if ((x < boardSize) && (y < boardSize))
    {
	[gameController boardHasChangedPosX:x posY:y];
    }
}


- (void)mouseDown:(NSEvent *)event 
{
//    [self mouseDragged:event];
    
}

- (void)awakeFromNib
{
//    int i = 0;
//    NSLog (@"%@", [[NSBundle mainBundle] builtInPlugInsPath]);
//    NSLog (@"%@", [[NSBundle mainBundle] bundlePath]);
//    for (i = 0; i < [[[NSProcessInfo processInfo] arguments] count]; ++i)
//        NSLog (@"%@", [[[NSProcessInfo processInfo] arguments] objectAtIndex:i]);
    
    boardSize = [gameController boardSize];
    animation = 0;
    history = [History sharedInstance];
    [PluginController sharedInstance];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.13
                  target:self
                selector:@selector(update)
                userInfo:self
                 repeats:YES];
	    
    markPos.x = -1;
    
    [self setPostsFrameChangedNotifications:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(frameChanged:)
        name:NSViewFrameDidChangeNotification
        object:self];
}

- (void)frameChanged:(NSNotification *) notification
{
    PluginController *plugin = [PluginController sharedInstance];
    boardSize = [gameController boardSize];
    squareSize = ([self bounds].size.height)/boardSize;

    [blackPiece release];
    [whitePiece release];
    [board release];
    [mark release];
    blackPiece = [[plugin imageNamed:@"black"] copy];
    whitePiece = [[plugin imageNamed:@"white"] copy];
    board = [[plugin imageNamed:@"board"] copy];
    mark = [[plugin imageNamed:@"mark"] copy];

    [whitePiece setScalesWhenResized:YES];
    [whitePiece setSize:NSMakeSize(squareSize, squareSize)];

    [blackPiece setScalesWhenResized:YES];
    [blackPiece setSize:NSMakeSize(squareSize, squareSize)];

    [board setScalesWhenResized:YES];
    [board setSize:NSMakeSize(squareSize*kBoardMaxCells,
                              squareSize*kBoardMaxCells)];

    [mark setScalesWhenResized:YES];
    [mark setSize:NSMakeSize(squareSize, squareSize)];
}

- (void)dealloc
{
    [super dealloc];
}

- (void)update
{
    if (animation)
    {
//	NSLog (@"animation = %d", animation);
	[self setNeedsDisplay:YES];
	if (animation == 1)
	    [gameController boardFinishedAnimation];
	--animation;	    
    }
}

- (void)animate
{
    animation = kAnimationSteps;
}

- (BOOL)isAnimating
{
    return (animation > 0);
}

@end
